/**
 * 
 */
package by.imotaeva.printing_services.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.imotaeva.printing_services.dataaccess.BlankOrderDao;
import by.imotaeva.printing_services.datamodel.BlankOrder;
import by.imotaeva.printing_services.datamodel.BlankOrder_;
import by.imotaeva.printing_services.datamodel.PrintingProductOrder_;

/**
 * @author Inna
 *
 */
@Repository
public class BlankOrderDaoImpl extends AbstractDaoImpl<Long, BlankOrder>
		implements BlankOrderDao {

	protected BlankOrderDaoImpl() {
		super(BlankOrder.class);
	}

	@Override
	public List<Long> getBlankOrderIds() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
		Root<BlankOrder> root = criteria.from(BlankOrder.class);

		criteria.select(root.get(BlankOrder_.id));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		List<Long> results = query.getResultList();
		return results;
	}

	@Override
	public Long getCount() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
		Root<BlankOrder> root = criteria.from(BlankOrder.class);

		criteria.select(cBuilder.count(root));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		return query.getSingleResult();
	}

	@Override
	public BlankOrder getFullBlankOrder(Long id) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<BlankOrder> criteria = cBuilder
				.createQuery(BlankOrder.class);
		Root<BlankOrder> root = criteria.from(BlankOrder.class);

		criteria.select(root);
		root.fetch(BlankOrder_.paper);
		root.fetch(BlankOrder_.printingProductOrder).fetch(
				PrintingProductOrder_.customer);

		criteria.where(cBuilder.equal(root.get(BlankOrder_.id), id));

		TypedQuery<BlankOrder> query = getEm().createQuery(criteria);
		BlankOrder result = query.getSingleResult();
		return result;
	}

}
